package com.beiing.tianshuai.tianshuai.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseRecyclerViewAdapter;
import com.beiing.tianshuai.tianshuai.entity.MyOrderBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.TimeUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.ParseException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

/**
 * Created by Jinda Yang on 2017/7/27 0027.
 * Description : 订单列表适配器
 */

public class MyOrderAdapter extends BaseRecyclerViewAdapter<MyOrderBean.DataBean.ResultBean> {

    private Context mContext;
    private OnClickListener mListener;

    public MyOrderAdapter(Context context) {
        this.mContext = context;
    }

    public void setListener(OnClickListener listener) {
        mListener = listener;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder holder;
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_order_normal, parent, false);
        holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, final int position) {
        MyOrderBean.DataBean.ResultBean order = mList.get(position);
        if (holder instanceof ViewHolder) {
            ((ViewHolder) holder).setData(order);
            ((ViewHolder) holder).setListener(order);
        }
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.civ_user_avatar)
        CircleImageView mCivUserAvatar;
        @BindView(R.id.txt_user_name)
        TextView mTxtUserName;
        @BindView(R.id.txt_order_state)
        TextView mTxtOrderState;
        @BindView(R.id.iv_order_cover)
        QMUIRadiusImageView mIvOrderCover;
        @BindView(R.id.txt_order_title)
        TextView mTxtOrderTitle;
        @BindView(R.id.txt_order_time)
        TextView mTxtOrderTime;
        @BindView(R.id.txt_order_address)
        TextView mTxtOrderAddress;
        @BindView(R.id.txt_order_price)
        TextView mTxtOrderPrice;
        @BindView(R.id.txt_order_ticket_type)
        TextView mTxtOrderTicketType;
        @BindView(R.id.txt_order_num)
        TextView mTxtOrderNum;
        @BindView(R.id.txt_order_goods_num)
        TextView mTxtOrderGoodsNum;
        @BindView(R.id.txt_order_total_price)
        TextView mTxtOrderTotalPrice;
        @BindView(R.id.ll_btn_container)
        LinearLayout mLlBtnContainer;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }

        private void setData(final MyOrderBean.DataBean.ResultBean order) {

            if (order.getIsStatus() != null) {
                String type = order.getIsStatus();
                // 订单状态
                switch (type) {
                    case "0":
                        mTxtOrderState.setText("待使用");
                        break;
                    case "1":
                        mTxtOrderState.setText("待发货");
                        break;
                    case "2":
                        mTxtOrderState.setText("待收货");
                        break;
                    case "3":
                        mTxtOrderState.setText("交易成功");
                        break;
                    case "4":
                        mTxtOrderState.setText("交易成功");
                        break;
                    case "5":
                        mTxtOrderState.setText("退款中");
                        break;
                    case "6":
                        mTxtOrderState.setText("退款成功");
                        break;
                    case "7":
                        mTxtOrderState.setText("卖家拒绝售后");
                        break;
                    default:
                        break;
                }
            }

            // 设置商家头像
            RequestOptions avatarOptions = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .placeholder(R.drawable.default_avatar)
                    .centerCrop()
                    .override(100, 100);
            Glide.with(mContext.getApplicationContext())
                    .load(TextUtils.isEmpty(
                            UserInfoBean.getAvatar(mContext)) ?
                            R.drawable.default_avatar :
                            HttpRequestConstant.USER_PIC_HEAD + order.getPhoto())
                    .apply(avatarOptions)
                    .into(mCivUserAvatar);

            // 设置商品封面
            RequestOptions coverOptions = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .placeholder(R.drawable.img_loading_background)
                    .centerCrop()
                    .override(400, 240);
            Glide.with(mContext.getApplicationContext())
                    .load(TextUtils.isEmpty(
                            order.getCover()) ?
                            R.drawable.img_loading_background :
                            HttpRequestConstant.ACTIVITY_PIC_HEAD + order.getCover())
                    .apply(coverOptions)
                    .into(mIvOrderCover);

            // 设置商家名字
            mTxtUserName.setText(order.getName());
            // 设置商品名称
            mTxtOrderTitle.setText(order.getAname());

            // 设置活动时间
            try {
                if (!TextUtils.isEmpty(order.getActionTime())) {
                    mTxtOrderTime.setText(
                            MessageFormat.format(
                                    "时间：{0}",
                                    TimeUtils.longToString(
                                            Long.parseLong(order.getActionTime()),
                                            "MM.dd HH:mm")
                            )
                    );
                } else {
                    mTxtOrderTime.setText("");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }

            // 活动举办地址
            mTxtOrderAddress.setText(MessageFormat.format("地点：{0}", order.getActivity()));
            // 商品单价
            String much = order.getMuch();
            mTxtOrderPrice.setText(("0".equals(much)) ? "免费" : "￥" + much);
            // 商品数量1
            mTxtOrderNum.setText(MessageFormat.format("x{0}", order.getCount()));
            // 商品数量2
            mTxtOrderGoodsNum.setText(MessageFormat.format("共{0}件商品", order.getCount()));

            // 订单商品总价
            if (order.getMuch() != null) {
                char moneySymbol = 165;
                double totalPrice = Double.parseDouble(order.getMuch()) * Double.parseDouble(order.getCount());
                BigDecimal bigDecimal = new BigDecimal(totalPrice);
                String strTotalPrice = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                mTxtOrderTotalPrice.setVisibility(View.VISIBLE);
                mTxtOrderTotalPrice.setText(MessageFormat.format(
                        "合计：{0} {1}", String.valueOf(moneySymbol), strTotalPrice));
            }
        }

        public void setListener(final MyOrderBean.DataBean.ResultBean bean) {

            TextView btnApplyForAfterSales;
            TextView btnDeleteOrder;

            mLlBtnContainer.removeAllViews();
            if (bean.getIsStatus() != null) {
                String isStatus = bean.getIsStatus();
                switch (isStatus) {
                    case "0":
                        btnApplyForAfterSales = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "申请售后",
                                AppConstant.BTN_TYPE_APPLY_FOR_AFTER_SALES
                        );
                        TextView btnCheckETicket = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_BLUE,
                                "电子票",
                                AppConstant.BTN_TYPE_E_TICKET
                        );
                        mLlBtnContainer.addView(btnApplyForAfterSales);
                        mLlBtnContainer.addView(btnCheckETicket);
                        break;
                    case "1":
                        TextView btnRemindTheDelivery = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "提醒发货",
                                AppConstant.BTN_TYPE_REMIND_THE_DELIVERY
                        );
                        btnApplyForAfterSales = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "申请售后",
                                AppConstant.BTN_TYPE_APPLY_FOR_AFTER_SALES
                        );
                        mLlBtnContainer.addView(btnRemindTheDelivery);
                        mLlBtnContainer.addView(btnApplyForAfterSales);
                        break;
                    case "2":
                        TextView btnDelayInReceiving = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "延长收货",
                                AppConstant.BTN_TYPE_DELAY_IN_RECEIVING
                        );
                        TextView btnCheckThtLogistics = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "查看物流",
                                AppConstant.BTN_TYPE_CHECK_THE_LOGISTICS
                        );
                        TextView btnConfirmReceipt = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_BLUE,
                                "确认收货",
                                AppConstant.BTN_TYPE_CONFIRM_RECEIPT
                        );
                        mLlBtnContainer.addView(btnDelayInReceiving);
                        mLlBtnContainer.addView(btnCheckThtLogistics);
                        mLlBtnContainer.addView(btnConfirmReceipt);
                        break;
                    case "3":
                        btnDeleteOrder = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "删除订单",
                                AppConstant.BTN_TYPE_DELETE_ORDER
                        );
                        btnApplyForAfterSales = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "申请售后",
                                AppConstant.BTN_TYPE_APPLY_FOR_AFTER_SALES
                        );
                        TextView btnToEvaluate = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_BLUE,
                                "去评价",
                                AppConstant.BTN_TYPE_TO_EVALUATE
                        );
                        mLlBtnContainer.addView(btnDeleteOrder);
                        mLlBtnContainer.addView(btnApplyForAfterSales);
                        mLlBtnContainer.addView(btnToEvaluate);
                        break;
                    case "4":
                        btnDeleteOrder = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "删除订单",
                                AppConstant.BTN_TYPE_DELETE_ORDER
                        );
                        btnApplyForAfterSales = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "申请售后",
                                AppConstant.BTN_TYPE_APPLY_FOR_AFTER_SALES
                        );
                        mLlBtnContainer.addView(btnDeleteOrder);
                        mLlBtnContainer.addView(btnApplyForAfterSales);
                        break;
                    case "5":
                        TextView btnCancelTheAfterSale = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "取消售后",
                                AppConstant.BTN_TYPE_CANCEL_THE_AFTER_SALE
                        );
                        mLlBtnContainer.addView(btnCancelTheAfterSale);
                        break;
                    case "6":
                        btnDeleteOrder = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "删除订单",
                                AppConstant.BTN_TYPE_DELETE_ORDER
                        );
                        mLlBtnContainer.addView(btnDeleteOrder);
                        break;
                    case "7":
                        btnDeleteOrder = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "删除订单",
                                AppConstant.BTN_TYPE_DELETE_ORDER
                        );
                        TextView btnApplyForAfterSalesAgain = getItemBtn(
                                bean,
                                AppConstant.BTN_BG_COLOR_GRAY,
                                "重新申请",
                                AppConstant.BTN_TYPE_APPLY_THE_AFTER_SALE_AGAIN
                        );
                        mLlBtnContainer.addView(btnDeleteOrder);
                        mLlBtnContainer.addView(btnApplyForAfterSalesAgain);
                        break;
                    default:
                        break;
                }
            }

            itemView.setOnClickListener(new BGAOnNoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    mListener.onItemClickListener(getAdapterPosition(), bean);
                }
            });
        }

        private TextView getItemBtn(final MyOrderBean.DataBean.ResultBean bean, int color, String text, int type) {
            TextView textView = new TextView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(DensityUtils.dp2px(mContext, 10), 0, 0, 0);
            textView.setLayoutParams(params);
            textView.setText(text);
            textView.setTextSize(13);
            int horizontal = DensityUtils.dp2px(mContext, 16);
            int vertical = DensityUtils.dp2px(mContext, 6);
            textView.setPadding(horizontal, vertical, horizontal, vertical);
            //设置背景颜色
            switch (color) {
                case AppConstant.BTN_BG_COLOR_GRAY:
                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_btn_100_gray));
                    textView.setTextColor(ContextCompat.getColor(mContext, R.color.color_black_333333));
                    break;
                case AppConstant.BTN_BG_COLOR_BLUE:
                    textView.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_btn_100_blue));
                    textView.setTextColor(ContextCompat.getColor(mContext, R.color.white));
                    break;
                default:
                    break;
            }

            //根据type设置按钮的点击事件
            switch (type) {
                case AppConstant.BTN_TYPE_DELETE_ORDER:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onDeleteClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_APPLY_FOR_AFTER_SALES:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onApplyForAfterSalesClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_TO_EVALUATE:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onToEvaluateClickListener(getAdapterPosition(), bean);
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_DELAY_IN_RECEIVING:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onDelayInReceivingClickListener(getAdapterPosition(), bean);
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_CHECK_THE_LOGISTICS:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onCheckLogisticsClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_CONFIRM_RECEIPT:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onConfirmReceiptClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_E_TICKET:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onPreviewClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_REMIND_THE_DELIVERY:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onRemindTheDeliveryClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_CANCEL_THE_AFTER_SALE:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onCancelTheAfterSaleClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                case AppConstant.BTN_TYPE_APPLY_THE_AFTER_SALE_AGAIN:
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onApplyAfterSaleAgainClickListener(getAdapterPosition(), bean.getId());
                            }
                        }
                    });
                    break;
                default:
                    break;
            }
            return textView;
        }
    }

    public interface OnClickListener {
//        /**
//         * 取消订单
//         *
//         * @param position 条目的位置
//         * @param orderId  订单id
//         */
//        void onCancelClickListener(int position, String orderId);

        /**
         * 查看电子票
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onPreviewClickListener(int position, String orderId);

        /**
         * 删除订单
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onDeleteClickListener(int position, String orderId);

        /**
         * 延迟收货
         *
         * @param position 条目位置
         * @param bean     订单id
         */
        void onDelayInReceivingClickListener(int position, MyOrderBean.DataBean.ResultBean bean);

        /**
         * 查看物流
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onCheckLogisticsClickListener(int position, String orderId);

        /**
         * 申请售后
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onApplyForAfterSalesClickListener(int position, String orderId);

        /**
         * 去评价
         *
         * @param position  条目位置
         * @param orderBean 订单id
         */
        void onToEvaluateClickListener(int position, MyOrderBean.DataBean.ResultBean orderBean);

        /**
         * 确认收货
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onConfirmReceiptClickListener(int position, String orderId);

        /**
         * 提醒发货
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onRemindTheDeliveryClickListener(int position, String orderId);

        /**
         * 取消售后
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onCancelTheAfterSaleClickListener(int position, String orderId);

        /**
         * 重新申请
         *
         * @param position 条目位置
         * @param orderId  订单id
         */
        void onApplyAfterSaleAgainClickListener(int position, String orderId);

        /**
         * 条目点击事件
         *
         * @param position 条目位置
         * @param bean     订单id
         */
        void onItemClickListener(int position, MyOrderBean.DataBean.ResultBean bean);
    }
}
